package com.peanut.interceptor;


import com.mvc.ResponseUtil;
import com.mvc.interceptor.HandlerInterceptor;
import com.peanut.constants.Constants;
import com.peanut.constants.Status;
import com.peanut.entity.AdminUser;
import com.peanut.entity.JsonResult;
import com.spring.annotation.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * 权限验证 ，进该验证拦截器的都是需要权限验证的
 */

@Component
public class PermissionInterceptor implements HandlerInterceptor {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 验证权限存在,不存在返回false
		HttpSession session = request.getSession(false);
		if (session != null) {
			
			AdminUser login_user = (AdminUser) session.getAttribute(Constants.LOGIN_USER);
			
			if(login_user.getId().equals(1) && login_user.getRoleId().equals(1)){
				// 系统内置的超级管理员，不验证权限，永远放行所有操作
				return true;
			}
			
			if(login_user.getRoleId()== null){
				// 账号暂时没有角色，无权操作任何内容
				ResponseUtil.ServerError2(response, JsonResult.status(Status.NO_ROLE));
				return false;
			}
			
			// 其他的哪怕是超级管理员，也会验证权限
			
			// 直接从全局中获取存放的所有权限url 列表    map< roleId,  List<String> >
			String requestURI = request.getRequestURI();
			Map<Integer,List<String>> permissionsMap =
					(Map<Integer,List<String>>) request.getServletContext().getAttribute(Constants.PERMISSIONS);
			if (permissionsMap != null && permissionsMap.containsKey(login_user.getRoleId())) {
				
				List<String> permissions = permissionsMap.get(login_user.getRoleId());
				for (String permissionUrl : permissions) {
					if (permissionUrl.equals(requestURI)) {
						return true;
					}
				}
			}
		}
		/**
		 *  必须写入错误给响应
		 */
		ResponseUtil.ServerError2(response, JsonResult.status(Status.NOT_PERMISSION));
		return false;
	}
}
